﻿using FlyIL.Advance;
using DebugHelp;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Console1
{
    public class MySymbolHandler : ISymbolHandler
    {



        SymbolHandler handler;


        IReadOnlyList<ModuleInfo> Modules;


        Dictionary<ModuleInfo, ICollection<SymbolInfo>> symbols = new Dictionary<ModuleInfo, ICollection<SymbolInfo>>();



        public MySymbolHandler(IntPtr handle)
        {

            handler = SymbolHandler.CreateFromHandle(handle, SymbolOptions.Include32BitModules);



            Modules = handler.EnumModules();

            foreach (var module in Modules)
            {

                symbols[module] = handler.EnumSymbols(module.Base);

            }

        }


        public SymInfo GetSymInfo(ulong address)
        {
            
            foreach(var pair in symbols)
            {
                var found = pair.Value.Where(o => o.Address == address);
                if (found.Any())
                {

                    return new SymInfo { Module = pair.Key.Name, Name = found.First().Name }; 
                }
            }

            return null; 

        }
    }
}
